// index.js

import {
  addWeight,
  deleteWeight,
  findWeightPage
} from "../../api/weightApi"
import {
  getDate,
  getDay,
  getHour,
  getMinute,
  getMonth,
  getYear
} from "../../utils/dateUtil"
import {
  verifyNumber,
  verifyPostNumber
} from "../../utils/verifyUtil"
import toastUtil from './../../utils/toastUtil'
import wxUtil from './../../utils/wxUtil'
import shareUtil from './../../utils/shareUtil'

// 获取应用实例
const app = getApp()

Page({
  data: {
    // 系统平台
    system: app.globalData.system,
    // 导航栏高度
    navigationHeight: app.globalData.navigationHeight,
    // 统一背景颜色
    unifyBgColor: app.globalData.unifyBgColor,
    // 顶部导航栏高度
    topNavigationHeight: app.globalData.topNavigationHeight,
    // 主色调
    mainColor: app.globalData.mainColor,
    // 分页提示
    pageMsg: '没有更多了',
    // 分页提示 ---- 加载中
    pageMsgLoading: '加载中',
    // 分页提示 ---- 没有更多了
    pageMsgNone: '没有更多了',
    // 表单
    form: {
      // 日期
      date: null,
      // 时间
      time: null,
      // 时间日期
      dateTime: null,
      // 体重
      weight: null
    },
    // 搜索表单
    searForm: {
      // 分页大小
      pageSize: 30,
      // 查询完毕
      overFlag: false
    },
    // 体重集合
    weightList: [],
    // 展示表单标志
    showFormFlag: false
  },

  onLoad() {

    // 开启微信内置分享功能
    shareUtil.startShare()

    this.setData({
      openId: wxUtil.getOpenId()
    })

    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    // 初始化时间
    this.initFormDate()
    // 查询数据
    this.findWeightList()
    // 生成数据
    //this.generatorWeight()
  },
  // 分享给朋友
  onShareAppMessage(){
    return shareUtil.shareToFreind()
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
    console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  // 加载更多数据
  scrolltolower() {
    console.log('scrolltolower...........')
    this.findNextVideoFileList()
  },

  // 不知道为什么不会触发该事件
  refresherrefresh() {
    console.log('refresherrefresh...........')

    // 下拉标志

    this.setData({
      topPullFlag: true,
      weightList: []
    })
    // 刷新数据
    this.findWeightList()
  },

  /**
   * 获取直播录像列表
   * @param {*} page 第几页
   * @param {*} callback 成功回调数据
   */
  findWeightList: function (page = 1, callback) {
    console.log('findWeightList........')
    // 页数超过了
    let searForm = this.data.searForm
    searForm.skip = this.data.weightList.length
    searForm.openid = wxUtil.getOpenId()
    findWeightPage(searForm).then((res) => {
      console.log('findWeightList data : ', res)
      // 添加成功
      let data = res.data
      // 查完了
      if (data.length <= 0) {
        let searForm = this.data.searForm
        searForm.overFlag = true
        this.setData({
          searForm: searForm
        })
        return
      }
      let weightList = this.data.weightList
      console.log("data : ", data)
      weightList = weightList.concat(data)
      this.setData({
        weightList: weightList
      })
      console.log("weightList : ", this.data.weightList)

    }, (data) => {
      console.log('reject data : ', data)
      toastUtil.showToast('查询体重失败，' + data.errMsg)
    }).finally(() => {
      this.setData({
        topPullFlag: false
      })
    })
  },

  //获取下一页直播录像列表
  findNextVideoFileList: function (callback) {
    this.findWeightList()
  },

  // 切换成加载中
  pageMsgLoading() {
    this.setData({
      pageMsg: this.data.pageMsgLoading
    })
  },
  // 切换成没有更多
  pageMsgNone() {
    this.setData({
      pageMsg: this.data.pageMsgNone
    })
  },

  // 初始化时间
  initFormDate() {
    let form = this.data.form
    let date = new Date()
    let year = getYear(date)
    let month = getMonth(date)
    let day = getDay(date)
    let hour = getHour(date)
    let minute = getMinute(date)
    form.date = year + '-' + month + "-" + day
    form.time = hour + ":" + minute
    this.setData({
      form: form
    })
  },

  // 绑定日期
  bindDateChange(e) {
    console.log(e)
    let date = e.detail.value
    let form = this.data.form
    form.date = date
    this.setData({
      form: form
    })
  },

  // 绑定时间
  bindTimeChange(e) {
    console.log(e)
    let time = e.detail.value
    let form = this.data.form
    form.time = time
    this.setData({
      form: form
    })
  },

  // 绑定体重
  bindInputChange(e) {
    console.log(e)
    let weight = e.detail.value
    let form = this.data.form
    form.weight = weight
    this.setData({
      form: form
    })
  },

  // 提交数据
  submit() {
    let form = this.data.form
    if (!verifyPostNumber(form.weight)) {
      toastUtil.showToast('请输入合法的体重')
      return
    }
    form.dateTime = getDate(form.date + " " + form.time + ":00")
    form.yearMonth = getYear(getDate(form.date + " " + form.time + ":00")) + "-" + getMonth(getDate(form.date + " " + form.time + ":00"))
    form.dateTimeStamp = form.dateTime.getTime()
    console.log('form : ', form)
    addWeight(form).then((data) => {
      console.log('success data : ', data)
      // 添加成功
      if (data._id) {
        toastUtil.showToast('添加体重成功')
        this.showForm()
        this.resetForm()
        this.refresherrefresh()
        return
      }
    }, (data) => {
      console.log('reject data : ', data)
      toastUtil.showToast('添加体重失败，' + data.errMsg)
    })

    //this.showForm()
  },

  // 展示表单
  showForm() {
    this.setData({
      showFormFlag: !this.data.showFormFlag
    })
  },



  // 重置表单
  resetForm() {
    this.setData({
      ['form.weight']: null
    })
  },

  /**
   * 删除体重
   */
  deleteWeightModal(e) {
    console.log(e)
    let id = e.currentTarget.dataset.id
    wx.showModal({
      title: '删除提示',
      content: '请问是否要删除这条数据？',
      success: (res) => {
        if (res.confirm) {
          console.log('用户点击确定')
          this.deleteWeight(id)
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
    /**
   * 删除体重
   */
  deleteWeight(id) {

    deleteWeight(id).then((data) => {
      console.log('success data : ', data)
      // 删除体重成功
      toastUtil.showToast('删除体重成功')
      this.refresherrefresh()
    }, (data) => {
      console.log('reject data : ', data)
      toastUtil.showToast('删除体重失败，' + data.errMsg)
    })
  },

  // 生成体重日志
  generatorWeight() {
    let startTime = new Date("2021-10-1")
    let startTimeStamp = startTime.getTime()
    let lastTime = new Date("2022-2-20")
    let lastTimeStamp = lastTime.getTime()
    for (; startTimeStamp < lastTimeStamp; startTimeStamp = startTimeStamp + 60 * 60 * 24 * 1000) {
      let form = this.data.form
      // 日期
      form.dateTime = new Date(startTimeStamp)
      // 体重
      form.weight = 70 + Math.random() * 20
      this.submit(form)
    }
  },
})